<template>
  <!--点赞文章按钮-->
  <van-button class="like-btns" :icon="value === 1 ? 'good-job' : 'good-job-o'" :class="{liked: value === 1}" :loading="loading" @click="onLike" />
</template>

<script>
import { addLike, deleteLike } from '@/api/article'
export default {
  name: 'LikeArticle',
  components: {},
  data () {
    return {
      loading: false
    }
  },
  props: {
    value: {
      required: true,
      type: Number
    },
    articleId: {
      required: true,
      type: [Number, String, Object]
    }
  },
  methods: {
    async onLike () {
      this.loading = true
      try {
        let status = -1 // -1表示取消点赞，1表示点赞
        if (this.value === 1) {
          // 已点赞，取消点赞
          await deleteLike(this.articleId)
        } else {
          // 已点赞，取消点赞
          await addLike(this.articleId)
          status = 1
        }
        // 更新视图
        this.$emit('input', status)
        this.$toast.success(status === 1 ? '点赞成功' : '取消点赞')
      } catch (err) {
        // this.$toast.fail('操作失败，请重试！')
        let message = '操作失败，请稍后重试！'
        if (err.response && err.response.status === 401) {
          message = '请登录后再点赞！'
          this.$router.push('/login')
        }
        this.$toast(message)
      }
      this.loading = true
    }
  }
}
</script>

<style scoped lang="less">
.van-button--default{
  border: none;
}
.liked{
  .van-icon{
    color: #ee0a24;
  }
}
.like-btns{
  font-size: 19px;
  padding-left: 0;
}
</style>
